package com.itheima.webSocket;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.entity.AccountMessage;
import com.itheima.entity.CustomerMessage;
import com.itheima.entity.ProjectReview;
import com.itheima.mapper.AccountAuthenticationMapper;
import com.itheima.service.impl.AccountAuthenticationServiceImpl;
import com.itheima.service.impl.ProjectReviewProgressServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author guanhuaer
 * 人工客服WebSocket处理器
 */

@Component
public class CustomerWebSocketHandler extends TextWebSocketHandler {
    private ObjectMapper objectMapper = new ObjectMapper();
    private final AccountAuthenticationMapper messageMapper;
    @Autowired
    public CustomerWebSocketHandler(AccountAuthenticationMapper messageMapper) {
        this.messageMapper = messageMapper;
    }
    // 定义sessions集合，用于存放所有连接到WebSocket的客户端session
    private static final CopyOnWriteArraySet<WebSocketSession> sessions = new CopyOnWriteArraySet<>();
    // 存放用户id和session的映射关系
    private static final Map<String, WebSocketSession> userSessions = new HashMap<>();
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("账户消息客户端连接成功：" + session.getId());
        // 解析请求参数，获取用户id
        // 获取用户id
        String userId = session.getUri().getPath().substring(session.getUri().getPath().lastIndexOf('/') + 1);
        // 将用户id和session添加到map中
        System.out.println("用户id：" + userId);
       // 判断是否已经有该用户的session
        if (!userSessions.containsKey(userId)) {
            userSessions.put(userId, session);
            // 存放session到sessions集合中
            sessions.add(session);
        }
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 接收并处理客户端消息
        System.out.println("接收到消息：" + message.getPayload());
        CustomerMessage customerMessage = objectMapper.readValue(message.getPayload(), CustomerMessage.class);
        // 判断 接收者id是否存在，存在则发送给对应用户，不存在则发送给管理员
        // 学生发送消息
        if (customerMessage.getIdentity()==0){
            Long toUserId = customerMessage.getToUserId();
            WebSocketSession targetSession = userSessions.get(String.valueOf(toUserId));
            if (targetSession != null && targetSession.isOpen()) {
                // 转换成json字符串
                String dataJson = objectMapper.writeValueAsString(customerMessage);
                // 发送消息给对应用户
                targetSession.sendMessage(new TextMessage(dataJson));
            }else {
                List<Long> adminIds = messageMapper.selectAdminIds();
                for (Long adminId : adminIds) {
                    WebSocketSession adminSession = userSessions.get(String.valueOf(adminId));
                    if (adminSession != null && adminSession.isOpen()) {
                        // 转换成json字符串
                        String dataJson = objectMapper.writeValueAsString(customerMessage);
                        // 发送消息给管理员
                        adminSession.sendMessage(new TextMessage(dataJson));
                    }
                }
            }
        }
        // 管理员发送消息
        if(customerMessage.getIdentity()==1){
            Long userId = customerMessage.getUserId();
            WebSocketSession targetSession = userSessions.get(String.valueOf(userId));
            if (targetSession != null && targetSession.isOpen()) {
                // 转换成json字符串
                String dataJson = objectMapper.writeValueAsString(customerMessage);
                // 发送消息给对应用户
                targetSession.sendMessage(new TextMessage(dataJson));
            }
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        System.out.println("账户消息客户端断开连接：" + session.getId());
        // 移除用户id和session的映射关系
        // 获取用户id
        String userId = session.getUri().getPath().substring(session.getUri().getPath().lastIndexOf('/') + 1);
        // 从map中移除用户id对应的session
        userSessions.remove(userId);
        // 移除session
        sessions.remove(session);
    }
}
